import { MerchantAPI } from '../../utils/api';

interface CategoryNode {
  categoryId: number;
  parentId?: number | null;
  name: string;
  sortOrder?: number;
  status?: number;
  children?: CategoryNode[];
  expanded?: boolean;
}

interface CategoryFormState {
  categoryId?: number;
  name: string;
  sortOrder: string;
  status: number;
}

Page({
  data: {
    statusBarHeight: 44,
    contentPaddingTop: 120,
    loading: false,
    saving: false,
    categories: [] as CategoryNode[],
    showForm: false,
    formMode: 'create' as 'create' | 'edit',
    formParentId: null as number | null,
    categoryForm: {
      name: '',
      sortOrder: '1',
      status: 1
    } as CategoryFormState
  },

  onLoad() {
    const statusBarHeight = this.getStatusBarHeight();
    this.setData({
      statusBarHeight,
      contentPaddingTop: statusBarHeight + 88
    });
    this.fetchCategories();
  },

  onShow() {
    this.fetchCategories();
  },

  getStatusBarHeight(): number {
    try {
      const systemInfo = wx.getSystemInfoSync();
      return systemInfo.statusBarHeight || systemInfo.safeArea?.top || 20;
    } catch (error) {
      return 44;
    }
  },

  async fetchCategories() {
    this.setData({ loading: true });
    try {
      const res = await MerchantAPI.getCategoryTree();
      const list = (res?.data || []) as CategoryNode[];
      const categories = this.normalizeCategoryTree(list);
      this.setData({ categories });
    } catch (error) {
      console.error('加载分类失败', error);
      wx.showToast({
        title: '加载分类失败',
        icon: 'none'
      });
    } finally {
      this.setData({ loading: false });
    }
  },

  normalizeCategoryTree(list: any[], level: number = 0): CategoryNode[] {
    return (list || []).map((item: any) => ({
      categoryId: item.categoryId,
      parentId: item.parentId ?? null,
      name: item.name,
      sortOrder: item.sortOrder ?? 1,
      status: item.status ?? 1,
      expanded: level === 0,
      children: this.normalizeCategoryTree(item.children || [], level + 1)
    }));
  },

  goBack() {
    wx.navigateBack({ delta: 1 });
  },

  toggleCategoryExpand(e: any) {
    const categoryId = Number(e.currentTarget.dataset.id);
    const categories = this.data.categories.map(category => {
      if (category.categoryId === categoryId) {
        return {
          ...category,
          expanded: !category.expanded
        };
      }
      return category;
    });
    this.setData({ categories });
  },

  handleAddPrimary() {
    this.openCreateForm(null);
  },

  handleAddChild(e: any) {
    const parentId = Number(e.currentTarget.dataset.id);
    this.openCreateForm(parentId);
  },

  async handleEditCategory(e: any) {
    const categoryId = Number(e.currentTarget.dataset.id);
    if (!categoryId) return;
    wx.showLoading({ title: '加载中...', mask: true });
    try {
      const res = await MerchantAPI.getCategoryDetail(categoryId);
      const detail = res?.data || {};
      this.setData({
        showForm: true,
        formMode: 'edit',
        formParentId: detail.parentId ?? null,
        categoryForm: {
          categoryId: detail.categoryId,
          name: detail.name || '',
          sortOrder: String(detail.sortOrder ?? 1),
          status: detail.status ?? 1
        }
      });
    } catch (error) {
      console.error('获取分类详情失败', error);
      wx.showToast({
        title: '获取详情失败',
        icon: 'none'
      });
    } finally {
      wx.hideLoading();
    }
  },

  handleDeleteCategory(e: any) {
    const categoryId = Number(e.currentTarget.dataset.id);
    if (!categoryId) return;
    wx.showModal({
      title: '删除分类',
      content: '删除后不可恢复，确定继续？',
      success: async (res) => {
        if (res.confirm) {
          wx.showLoading({ title: '删除中...', mask: true });
          try {
            await MerchantAPI.deleteCategory([categoryId]);
            wx.showToast({
              title: '已删除',
              icon: 'success'
            });
            this.fetchCategories();
          } catch (error) {
            console.error('删除分类失败', error);
          } finally {
            wx.hideLoading();
          }
        }
      }
    });
  },

  openCreateForm(parentId: number | null) {
    this.setData({
      showForm: true,
      formMode: 'create',
      formParentId: parentId,
      categoryForm: {
        name: '',
        sortOrder: '1',
        status: 1
      }
    });
  },

  closeForm() {
    if (this.data.saving) return;
    this.setData({
      showForm: false,
      categoryForm: {
        name: '',
        sortOrder: '1',
        status: 1
      }
    });
  },

  onFormInput(e: any) {
    const field = e.currentTarget.dataset.field;
    const value = e.detail.value;
    if (!field) return;
    this.setData({
      [`categoryForm.${field}`]: value
    });
  },

  onFormStatusChange(e: any) {
    const checked = e.detail.value;
    this.setData({
      'categoryForm.status': checked ? 1 : 0
    });
  },

  async submitCategoryForm() {
    const { formMode, categoryForm, formParentId } = this.data;
    if (!categoryForm.name.trim()) {
      wx.showToast({
        title: '请输入分类名称',
        icon: 'none'
      });
      return;
    }

    const payload: any = {
      name: categoryForm.name.trim(),
      sortOrder: Number(categoryForm.sortOrder) || 1,
      status: categoryForm.status,
      parentId: formParentId === null ? null : formParentId
    };

    this.setData({ saving: true });
    wx.showLoading({ title: '保存中...', mask: true });
    try {
      if (formMode === 'create') {
        await MerchantAPI.createCategory(payload);
        wx.hideLoading();
        this.setData({ saving: false });
        wx.showToast({ 
          title: '创建成功', 
          icon: 'success',
          duration: 1000
        });
        // 新建分类后自动关闭表单并刷新列表
        setTimeout(() => {
          this.closeForm();
          this.fetchCategories();
        }, 1000);
      } else {
        await MerchantAPI.updateCategory({
          ...payload,
          categoryId: categoryForm.categoryId
        });
        wx.hideLoading();
        this.setData({ saving: false });
        wx.showToast({ 
          title: '更新成功', 
          icon: 'success',
          duration: 1000
        });
        setTimeout(() => {
          this.closeForm();
          this.fetchCategories();
        }, 1000);
      }
    } catch (error) {
      console.error('保存分类失败', error);
      wx.hideLoading();
      this.setData({ saving: false });
      wx.showToast({
        title: '保存失败，请重试',
        icon: 'none'
      });
    }
  },

  noop() {}
});

